package com.vains.controller;

import com.vains.bean.Result;
import com.vains.client.AuthClient;
import com.vains.config.properties.RemoteTokenServicesProperties;
import com.vains.constant.Oauth2AuthorizationConstants;
import com.vains.util.JsonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 测试接口
 *
 * @author vains
 * @date 2021/4/4 22:38
 */
@RestController
@AllArgsConstructor
@Api(tags = "测试接口")
@RequestMapping("/test")
public class TestController {

    private final AuthClient authClient;

    private final RemoteTokenServicesProperties remoteTokenServicesProperties;

    @GetMapping("/test01")
    @ApiOperation("测试接口")
    @PreAuthorize("hasAuthority('/test/test01')")
    public Result<String> test01() {
        return Result.success();
    }

    @GetMapping("/getToken")
    @ApiOperation("测试授权码模式，由认证中心自动请求")
    public Result<?> getToken(String code) {
        if (StringUtils.isEmpty(code)) {
            return Result.error("授权码不能为空.");
        }
        MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
        parameters.add("code", code);
        parameters.add("grant_type", Oauth2AuthorizationConstants.AUTHORIZATION_CODE);
        RemoteTokenServicesProperties.Client client = remoteTokenServicesProperties.getClient();
        parameters.add("client_id", client.getClientId());
        parameters.add("client_secret", client.getClientSecret());
        parameters.add("redirect_uri", remoteTokenServicesProperties.getResource().getRedirectUri());
        Map<String, Object> map = authClient.postAccessToken(parameters);
        String successKey = "success";
        if (map.containsKey(successKey)) {
            return JsonUtils.objectCovertToObject(map, Result.class, Object.class);
        }
        return Result.success(map);
    }

}
